package com.ubtechinc.cruzr.launcher2.utlis;

import com.ubtechinc.cruzr.launcher2.callback.RxTimerListener;

import java.util.concurrent.TimeUnit;

import io.reactivex.Observable;
import io.reactivex.Observer;
import io.reactivex.android.schedulers.AndroidSchedulers;
import io.reactivex.disposables.Disposable;
import io.reactivex.functions.Function;
import io.reactivex.schedulers.Schedulers;

public class RxTimer {
    private Disposable mDisposable;
    private final int mMaxCount = Integer.MAX_VALUE; //总时间
    public void startTime(final RxTimerListener listener, long delay,long timeout) {
        Observable.interval(delay, timeout, TimeUnit.MILLISECONDS)
                .take(mMaxCount )//设置总共发送的次数
                .map(new Function<Long, Long>() {
                    @Override
                    public Long apply(Long aLong) {
                        //aLong从0开始
                        return mMaxCount - aLong;
                    }
                })
                .subscribeOn(Schedulers.io())
                .observeOn(AndroidSchedulers.mainThread())
                .subscribe(new Observer<Long>() {
                    @Override
                    public void onSubscribe(Disposable d) {
                        mDisposable = d;
                    }

                    @Override
                    public void onNext(Long value) {
                        listener.onTimeNext();
                    }

                    @Override
                    public void onError(Throwable e) {

                    }

                    @Override
                    public void onComplete() {
                        // TODO:2017/12/1
                        closeTimer();
                    }
                });
    }


    /**
     * 关闭定时器
     */
    public void closeTimer() {
        if (mDisposable != null && !mDisposable.isDisposed()) {
            mDisposable.dispose();
        }
    }
}
